// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()

exports.main = async (event, context) => {
  try {
    // 参数校验
    if (!event.collection) {
      throw new Error('缺少collection参数');
    }
    
    // 获取所有文档
    const res = await db.collection(event.collection).get()
    
    // 批量删除
    const deletePromises = res.data.map(item => {
      return db.collection(event.collection).doc(item._id).remove()
        .catch(err => {
          console.warn(`删除文档 ${item._id} 失败:`, err);
          return {success: false, id: item._id, error: err.message || String(err)};
        });
    });
    
    const results = await Promise.all(deletePromises);
    const successCount = results.filter(r => r && r.errMsg === 'document.remove:ok').length;
    
    return {
      success: true,
      total: res.data.length,
      deleted: successCount,
      failures: res.data.length - successCount,
      errors: results.filter(r => r && r.error).map(r => r.error)
    };
  } catch (err) {
    // 确保返回一致的错误结构
    return {
      success: false,
      error: {
        message: err.message || String(err),
        stack: err.stack,
        code: err.code
      }
    };
  }
}